package com.du.dupload;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.filechooser.FileNameExtensionFilter;

public class SwingBrowsePanel extends JPanel {
	private JButton button;
	private JButton button2;
	private JFileChooser fc = new JFileChooser();

	SwingBrowsePanel() {
		fc.setAcceptAllFileFilterUsed(false);
		fc.setFileFilter(new FileNameExtensionFilter("torrent files", "torrent"));
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		setPreferredSize(new Dimension(100, 400));
		setMinimumSize(new Dimension(100, 400));
		// BufferedImage buttonIcon;
		Image buttonIcon = Toolkit.getDefaultToolkit().getImage(
				SwingContainer.class.getResource("/res/torrent.png"));
		button = new JButton("Add torrent", new ImageIcon(buttonIcon));
		button.setVerticalTextPosition(JButton.BOTTOM);
		button.setHorizontalTextPosition(JButton.CENTER);
		button.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
		add(button);
		ActionListener al = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent ae) {
				switch (fc.showOpenDialog(SwingBrowsePanel.this)) {
				case JFileChooser.APPROVE_OPTION:
					TasksManager.getInstance().addTask(new TorrentDownloader(fc.getSelectedFile().getAbsolutePath()));
					break;

				case JFileChooser.CANCEL_OPTION:
					break;

				case JFileChooser.ERROR_OPTION:
					break;
				}
			}
		};
		button.addActionListener(al);
		
		buttonIcon = Toolkit.getDefaultToolkit().getImage(
				SwingContainer.class.getResource("/res/Location-HTTP.png"));
		button2 = new JButton("Add URL", new ImageIcon(buttonIcon));
		button2.setVerticalTextPosition(JButton.BOTTOM);
		button2.setHorizontalTextPosition(JButton.CENTER);
		button2.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
		add(button2);
		al = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent ae) {

		        JTextField field1 = new JTextField("URL");
		        JPanel panel = new JPanel(new GridLayout(0, 1));
		        panel.add(new JLabel("URL"));
		        panel.add(field1);
		        int result = JOptionPane.showConfirmDialog(null, panel, "Test",
		            JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
		        if (result == JOptionPane.OK_OPTION) {
		        	TasksManager.getInstance().addTask(new URLDownloader(field1.getText()));
		        } else {
		            System.out.println("Cancelled");
		        }
			}
		};
		button2.addActionListener(al);
	}

}
